package com.qdu.security;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.qdu.entity.Student;
import com.qdu.entity.Teacher;
import com.qdu.entity.Users;
import com.qdu.mapper.UsersMapper;
import com.qdu.service.CurrentTermService;
import com.qdu.service.StudentService;
import com.qdu.service.TeacherService;

//如果spring security验证用的用户信息来自数据库的话
//那么可以通过实现UserDetailsService接口来创建一个UserDetailsService类
//来指定验证用的用户信息如何来的
@Component
public class CustomUserDetailsService implements UserDetailsService{

	//因为需要操作user_info表，所以需要注入UserInfoMapper对象
	@Autowired
	private UsersMapper mapper;
	@Autowired
	HttpSession session;
	@Autowired
	private StudentService studentService;	
	@Autowired
	private CurrentTermService currentTermService;	
	@Autowired
	private TeacherService teacherService;	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if(username.length()==10) {
			Student stu = studentService.selectStudentById(username);
			session.setAttribute("loginStudent", stu);
		}else if(username.length()==8){
			Teacher teacher = teacherService.selectTeacherById(username);
			session.setAttribute("loginTeacher", teacher);
			String tid=teacher.getTid();
			session.setAttribute("loginTeacherId", tid);
		}
		session.setAttribute("currentTerm", currentTermService.getAllCurrentTerm());
		Users users=mapper.getOneUserById(username);
		if(null==users)
			throw new UsernameNotFoundException("无此用户");
		List<String> roles=mapper.selectRoleNamesById(username);
		List<GrantedAuthority> authorities=new ArrayList<>();
		for(String role:roles) {
			authorities.add(new SimpleGrantedAuthority("ROLE_"+role));
		}
		return new User(users.getUid(),users.getUpassword(),authorities);
	}
}
